package io.gitee.lglbc.easy.security.core.security;

import io.gitee.lglbc.easy.security.open.EasyLogin;
import io.gitee.lglbc.easy.security.open.SimpleUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 乐哥聊编程
 */
@Service
public class EasyUserDetailService implements UserDetailsService {
    @Autowired
    private EasyLogin easyLogin;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SimpleUser simpleUser = easyLogin.loadUser(username);
        if (Objects.isNull(simpleUser)) {
            throw new UsernameNotFoundException("user not found");
        }
        easyLogin.preCheck(simpleUser);
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String role : simpleUser.getRoles()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
        }
        for (String permission : simpleUser.getPermissions()) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        return new User(username, simpleUser.getPassword(), authorities);
    }
}
